Vue.component("config-item",{
    /**
     * useage : <config-item type="radio" :value="form[key]" label="开启直播" values="开启=1,关闭=2"></config-item>
     */
    props : {
        values:'',
        label : {
            default : '表单项'
        },
        type : {
            default : 'text'
        },
        config : {
            default : ''
        }
    },
    data:function (){
        return {
            radioName : 'RADIO_' + new Date().getTime() + '[]',
            radioValues:[]
        }
    },
    created:function(){
        if(this.type == 'radio'){
            var radioValues = [];
            $.each(this.values.split(','),function(key,value){
                //console.log([key,value])
                var arr = value.split('=');
                radioValues.push({
                    text : arr.shift(),
                    value: arr.join('=')
                })
            })
            this.radioValues = radioValues;
            console.log(this.config.paramValue)
        }
    },
    mounted:function(){
        
    },
    template : `
        <div class="form-group">
            <label>{{label}}</label>
            <p v-if="type=='radio'" >
                <label v-for="(v,k) in radioValues" class="checkbox-inline">
                    <input :name="radioName" type="radio" :value="config.paramValue" :checked="config.paramValue == v.value"> {{v.text}}
                </label>
            </p>
            <p v-if="type=='xxx'" >
                <input type="text" class="form-control" :value="config.paramValue" :placeholder="config.remark" />
            </p>
        </div>
    `
});

Vue.component("web-uploader",{
    props : {
        debug : {
            default : true
        },
        action : {
            default : baseURL + 'sys/oss/upload'
        },
        id : 'uploader',
        thubmStyle : {
            default : function(){
                return {
                    width : 110,
                    height : 110
                }
            }
        }
    },
    event:['response'],
    data:function (){
        return {
            
        }
    },
    created:function (){
        
    },
    methods:{
        addlog : function(str){
            if(this.debug){
                console.log(str);
            }
        }
    },
    mounted:function (){
        var vm = this;
        vm.addlog(vm.thubmStyle);
        var $list  = $(this.$el).find('.uploader-list');
        var options = {
            // 选完文件后，是否自动上传。
            auto: true,
            // swf文件路径
            swf: baseURL + 'statics/plugins/webuploader/Uploader.swf',
            // 文件接收服务端。
            server: vm.action,
            // 选择文件的按钮。可选。
            // 内部根据当前运行是创建，可能是input元素，也可能是flash.
            //pick: $('.picker',$(vm.$el)),
            pick: ".picker",
            // 只允许选择图片文件。
            accept: {
                title: 'Images',
                extensions: 'gif,jpg,jpeg,bmp,png',
                mimeTypes: 'image/*'
            }
        }
        var uploader = WebUploader.create(options);
        uploader.on("all",function(){
            var args = [].slice.apply(arguments);
            vm.addlog(args);
        })
        uploader.on("beforeFileQueued",function(file){
            var args = [].slice.apply(arguments);
            console.log("beforeFileQueued");
            console.log(args)
        })
        uploader.on( 'fileQueued', function( file ) {
            var $li = $(
                    '<div id="' + file.id + '" class="file-item thumbnail">' +
                        '<img>' +
                        '<div class="info">' + file.name + '</div>' +
                    '</div>'
                    );

            $img = $li.find('img');
            $list.append( $li );
            uploader.makeThumb( file, function( error, src ) {
                vm.addlog(['make-thumb-error',error]);
                if ( error ) {
                    $img.replaceWith('<span>不能预览</span>');
                    return;
                }
        
                $img.attr( 'src', src );
            }, vm.thubmStyle.width, vm.thubmStyle.height);
        });
        // 文件上传过程中创建进度条实时显示。
        uploader.on( 'uploadProgress', function( file, percentage ) {

            var $li = $( '#'+file.id ),
                $percent = $li.find('.progress span');

            // 避免重复创建
            if ( !$percent.length ) {
                $percent = $('<p class="progress"><span></span></p>')
                        .appendTo( $li )
                        .find('span');
            }

            vm.addlog(['upload-progress',$percent.length,percentage]);

            $percent.css( 'width', percentage * 100 + '%' );
        });

        // 文件上传成功，给item添加成功class, 用样式标记上传成功。
        uploader.on( 'uploadSuccess', function( file ,res) {

            vm.addlog(['upload-success',res]);

            vm.$emit('response',res);

            if(res.code>0){
                console.log(res.url);
                vm.addlog(JSON.stringify(res));
            }

            $( '#'+file.id ).addClass('upload-state-done');
        });

        // 文件上传失败，显示上传出错。
        uploader.on( 'uploadError', function( file ) {
            var $li = $( '#'+file.id ),
                $error = $li.find('div.error');

            // 避免重复创建
            if ( !$error.length ) {
                $error = $('<div class="error"></div>').appendTo( $li );
            }

            vm.addlog(['upload-error',file]);

            $error.text('上传失败');
        });

        //完成上传完了，成功或者失败，先删除进度条。
        uploader.on( 'uploadComplete', function( file ) {
            vm.addlog(['upload-complete',file]);
            $( '#'+file.id ).find('.progress').remove();
        });

        this.$on('refresh',function(){
            uploader.refresh();
        })
    },
    template : `
        <div :id="id||'uploader'" class="uploader">
            <!--用来存放item-->
            <div class="uploader-list"></div>
            <div class="picker">选择图片</div>
        </div>
    `
});

/**
 * [pagination 分页组件]
 * useage : <pagination :total="total" :current.sync="current" v-on:pagechange="pagechange"></pagination>
 * @param  {Number} total         [数据总条数]
 * @param  {Number} pagesize     [每页显示条数 default:10]
 * @param  {Number} current     [当前页码 default:1]
 * @param  {Number} pagegroup     [分页条数(奇数) default:5]
 * @param  {Event} pagechange     [页码改动时 dispatch ]
 * @return {[type]}   [description]
 */
Vue.component('pagination', {
    template: '<nav>\n' +
        '        <ul class="pagination">\n' +
        '            <li :class="{\'disabled\': current == 1}"><a href="javascript:;" v-on:click="setCurrent(1)"> 首页 </a></li>\n' +
        '            <li :class="{\'disabled\': current == 1}"><a href="javascript:;" v-on:click="setCurrent(current - 1)"> 上一页 </a></li>\n' +
        '            <li v-for="p in grouplist" :class="{\'active\': current == p.val}"><a href="javascript:;" v-on:click="setCurrent(p.val)"> {{ p.text }} </a></li>\n' +
        '            <li :class="{\'disabled\': current == page}"><a href="javascript:;" v-on:click="setCurrent(current + 1)"> 下一页</a></li>\n' +
        '            <li :class="{\'disabled\': current == page}"><a href="javascript:;" v-on:click="setCurrent(page)"> 尾页 </a></li>\n' +
        '        </ul>\n' +
        '        <ul class="pagination pull-right">\n' +
        '            <li><span> 共 {{ total }}  条数据 </span></li>\n' +
        '            <li><span> 每页显示 {{ pagesize }}  条数据 </span></li>\n' +
        '            <li><span> 共 {{ page }} 页 </span></li>\n' +
        '            <li><span> 当前第 {{ current }} 页 </span></li>\n' +
        '        </ul>\n' +
        '    </nav>',
    props: {
        total: {            // 数据总条数
            type: Number,
            default: 0
        },
        pagesize: {            // 每页显示条数
            type: Number,
            default: 10
        },
        current: {            // 当前页码
            type: Number,
            default: function (){
                return 1;
            }
        },
        pagegroup: {        // 分页条数 -- 奇数
            type: Number,
            default: 5,
            coerce: function (v) {
                v = v > 0 ? v : 5;
                return v % 2 === 1 ? v : v + 1;
            }
        }
    },
    computed: {
        page: function () { // 总页数
            return Math.ceil(this.total / this.pagesize);
        },
        grouplist: function () { // 获取分页页码
            var len = this.page, temp = [], list = [], count = Math.floor(this.pagegroup / 2), center = this.current;
            if (len <= this.pagegroup) {
                while (len--) { temp.push({ text: this.page - len, val: this.page - len }); };
                return temp;
            }
            while (len--) { temp.push(this.page - len); };
            var idx = temp.indexOf(center);
            (idx < count) && (center = center + count - idx);
            (this.current > this.page - count) && (center = this.page - count);
            temp = temp.splice(center - count - 1, this.pagegroup);
            do {
                var t = temp.shift();
                list.push({
                    text: t,
                    val: t
                });
            } while (temp.length);
            if (this.page > this.pagegroup) {
                (this.current > count + 1) && list.unshift({ text: '...', val: list[0].val - 1 });
                (this.current < this.page - count) && list.push({ text: '...', val: list[list.length - 1].val + 1 });
            }
            return list;
        }
    },
    methods: {
        setCurrent: function (idx) {
            console.log(this)
            if (this.current != idx && idx > 0 && idx < this.page + 1) {
                this.current = idx;
                this.$emit('pagechange', this.current);
            }
        }
    }

});